/**
 * @author مۇختەرجان مەخمۇت (mutearjan mahmood)
 * @email yeganaaa@163.com
 * @create date 2020-09-05 19:04:16
 * @modify date 2020-09-05 19:04:16
 * @desc [description]
*/

import { IBroadcastClientInterface, IBroadcastServerInterface } from "./Shared";
import {IStateModule, RpcBridge, StateModuleInMemoryImplementation, KeepAliveRpcBridgeHost, delay} from "dream_rpc";
import WebSocket from "ws";
import { WebSocketBridgeHost } from "dream_rpc_node_websocket";
import { TcpSocketBridgeHost } from "dream_rpc_node_tcp_socket";
import * as Net from "net"
import {AutoRecoverableRpcBridgeHost} from "dream_rpc/bin/Core/AutoRecoverableRpcBridgeHost";

class MyBroadcastClientImplementation implements IBroadcastClientInterface {
    /**
     * Related state management, please visit github (or gitee) documentation
     */
    stateModule: IStateModule = new StateModuleInMemoryImplementation()
    /**
     * Calling when server side occur events related this client.
     * @param error error
     */
    public async sendErrorMessage(error: string): Promise<void> {
        console.error(error)
    }

    public async onBroadcastReceived(args: { message: string; sender: string; }): Promise<void> {
        console.log(`A message received by [${args.sender}] with the following content:`)
        console.log(args.message)
    }
}

async function connect() {
    let client = new RpcBridge<IBroadcastClientInterface, IBroadcastServerInterface>(
        // new KeepAliveRpcBridgeHost(new WebSocketBridgeHost(async () => new WebSocket("ws://192.168.0.110:8000/Broadcast"))),
        new AutoRecoverableRpcBridgeHost(
            async () => new KeepAliveRpcBridgeHost(
                    // new TcpSocketBridgeHost(async () => Net.connect({host: "192.168.0.107", port: 8001})),
                new WebSocketBridgeHost(async () => new WebSocket("ws://192.168.0.107:8000/Broadcast")),
            ),
            1000,
            async () => {
                console.log("Connection error, still retrying after 1000 milliSeconds...")
            },
            async () => {
                console.log("Connection is lost, system will retry connect after 1000 milliSeconds...")
            },
            async () => {
                console.log("System is reconnected.")
                client.remoteInterface.sendBroadcast({
                    sender: "Dream-Lab",
                    message: "I'm reconnected!"
                })
            }
        ),
        new MyBroadcastClientImplementation(),
    )
    await client.connect()
    await client.remoteInterface.sendBroadcast({
        sender: "مۇختەرجان",
        message: "Hello there, I'm coming..."
    })
}
async function main() {
    connect()
}
main()